<template>
  <el-dialog :title="uploadConfig.title || '文件上传'" :visible.sync="dialogFormVisible" @close="closeUpload">
    <div class="upload-area overflow-y">
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules"
        :label-width="uploadConfig.labelWidth || '100px'">
        <el-form-item v-for="(item, index) in uploadConfig.conditions" :key="index" :prop="item.prop"
          :label="`${item.label}：`" :label-width="item.labelWidth">
          <template v-if="item.type === 'input'">
            <el-input v-model="uploadForm[item.prop]" :placeholder="`请输入${item.label}`"
              :style="`width: ${uploadConfig.inputWidth}`" :disabled="item.disabled" clearable></el-input>
          </template>
          <template v-if="item.type === 'select'">
            <el-select v-model="uploadForm[item.prop]" :placeholder="`请选择${item.label}`"
              :style="`width: ${uploadConfig.inputWidth}`" :disabled="item.disabled" clearable>
              <el-option v-for="option in item.options" :key="option.value" :label="option.name" :value="option.value">
              </el-option>
            </el-select>
          </template>
          <template v-if="item.type === 'file'">
            <el-upload ref="uploadComp" class="upload-demo" :name="item.prop" :data="{ ...uploadData }"
              :headers="uploadHeaders"
              :accept="(uploadConfig.accept || '').toLocaleLowerCase() + ',' + (uploadConfig.accept || '').toLocaleUpperCase()"
              :limit="uploadConfig.limit" :action="actionUrl" :multiple="uploadConfig.multiple" drag :auto-upload="false"
              :on-exceed="fileExceed" :on-change="fileChange" :on-remove="fileChange" :on-success="uploadSuccess"
              :on-error="uploadFailed">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="app-font-size12" slot="tip">{{ uploadConfig.uploadTips }}</div>
              <div class="app-font-size12" slot="tip">当前页面最多可导入{{ uploadConfig.limit }}个文件（已选择{{ fileCount }}个）</div>
              <div class="app-font-size12 app-error-color__text" slot="tip">选中或拖入文件后，需要点击右下角“上传并导入”按钮进行上传</div>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeUpload">取 消</el-button>
      <el-button type="primary" @click="confirmUpload" :loading="uploadLoading">上传并导入</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  props: {
    uploadConfig: {
      type: Object,
      default() {
        return {};
      },
    }
  },
  computed: {
    actionUrl() {
      return this.$utils.getApiUrl(this.uploadConfig.action || this.defaultAction);
    },
    uploadForm() {
      return { ...(this.uploadConfig.form || {}) }
    },
  },
  data() {
    return {
      defaultAction: '/plan/fileUpload',
      fileCount: 0,
      dialogFormVisible: false,
      uploadLoading: false,
      uploadHeaders: {
        token: this.$store.getters.userToken,
      },
      uploadRules: { ...(this.uploadConfig.formRules || {}) },
      uploadData: { ...this.uploadConfig.form },
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    open() {
      this.dialogFormVisible = true;
      this.uploadLoading = false;
    },
    fileChange(file, fileList) {
      this.fileCount = fileList.length;
    },
    fileExceed(e) {
      this.$message.warning(`选择的文件超出上传个数限制（${this.uploadConfig.limit}个），请重新选择文件或者删除已选择的文件`);
      this.$log.debug('选择的文件超出限制，当前选择的文件列表为：', e);
    },
    confirmUpload() {
      if (!this.fileCount) {
        this.$message.warning('请选择需要导入的文件');
        return;
      }
      this.$refs['uploadForm'].validate((result) => {
        if (result) {
          this.uploadLoading = true;
          this.$log.debug('用户点击提交文件导入按钮，导入参数为：', this.uploadForm);
          if (this.$refs['uploadComp'] && this.$refs['uploadComp'].length) {
            for (const key in (this.uploadForm || {})) {
              this.$refs['uploadComp'][0].data[key] = this.uploadForm[key];
            }
            this.$refs['uploadComp'][0].submit();
          }
        }
      });
    },
    uploadFailed(e) {
      this.$log.debug('文件上传失败，错误信息为：', e);
      this.$message.error('文件上传失败');
      this.uploadLoading = false;
    },
    uploadSuccess(e) {
      this.$log.debug('文件上传成功：', e);
      this.$message.success('文件上传成功');
      this.uploadLoading = false;
      this.closeUpload();
      this.$emit('success');
    },
    closeUpload() {
      this.$refs['uploadForm'].resetFields();
      if (this.$refs['uploadComp'] && this.$refs['uploadComp'].length) {
        this.$refs['uploadComp'][0].abort();
        this.$refs['uploadComp'][0].clearFiles();
      }
      this.uploadLoading = false;
      this.dialogFormVisible = false;
    },
  }
}
</script>
<style lang="scss" scoped>
.upload-area {
  max-height: 450px;
}
</style>